package com.gree.elasticsearch.initializer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.stereotype.Component;

/**
 * 总有刁民想害朕，请叫我小花狗
 * create by zxw on 2020/5/22
 */
@Component
public class JpaTransactionManagerPostProcessor implements BeanPostProcessor {

    private Logger log = LoggerFactory.getLogger(JpaTransactionManagerPostProcessor.class.getName());

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean.getClass().isAssignableFrom(JpaTransactionManager.class)) {
            log.info("set JpaTransactionManager allow nested transaction in out-of-box transaction. bean name is {} ", beanName);
            JpaTransactionManager jpaTransactionManager = (JpaTransactionManager)bean;
            jpaTransactionManager.setNestedTransactionAllowed(Boolean.TRUE);
            return jpaTransactionManager;
        }
        return bean;
    }
}
